package restfuljobs

import org.springframework.dao.DataIntegrityViolationException
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import groovyx.net.http.Method
import groovy.util.slurpersupport.NodeChild
import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH

class JobListingController extends AbstractRestController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	
	JobListingController() {
		path = 'jobListing'
	}
	
	def index() {
        redirect(action: "list", params: params)
    }

    def list() {

    	def jobListingInstanceList = []
		
		httpBuilder.get( path: path,
			headers : [Accept : 'application/xml']) { resp, xml ->
			
			xml.jobListing.each {
				def jobListing = new JobListingWrapper()
				jobListing.id = it.attributes()['id'].toLong()				
				jobListing.setFromXML(it)					
				jobListingInstanceList.add(jobListing)
			}
		}
        //params.max = Math.min(params.max ? params.int('max') : 10, 100)
        //[jobListingInstanceList: JobListing.list(params), jobListingInstanceTotal: JobListing.count()]
		[jobListingInstanceList: jobListingInstanceList, jobListingInstanceTotal: jobListingInstanceList.size()]
    }
    
    def search() {

    	def jobListingInstanceList = []
		
		httpBuilder.get( path: path, 
			query: [jobTitle: params.jobTitle, employer: params.employer, jobCategory: params.jobCategory, location: params.location],
			headers : [Accept : 'application/xml']) { resp, xml ->
			
			xml.jobListing.each {
				def jobListing = new JobListingWrapper()
				jobListing.id = it.attributes()['id'].toLong()				
				jobListing.setFromXML(it)					
				jobListingInstanceList.add(jobListing)			
			}
		}
        
		def map = [jobListingInstanceList: jobListingInstanceList, jobListingInstanceTotal: jobListingInstanceList.size()]
		flash.message = "Search Result"
		render(view: "list", model: map)
    }
    
    def showSearch() {
    	[jobListingInstance: new JobListing(params)]
    }

    def create() {
        [jobListingInstance: new JobListing(params)]	
    }

    def show() {
		def jobListingInstance
		
		httpBuilder.request(rootPath, Method.GET, XML ) {
			uri.path = path + "/$params.id"
			//uri.query = [ v:'1.0', q: 'Calvin and Hobbes' ]
			
			response.success = { resp, xml ->			  
			  xml.each {												
				jobListingInstance = new JobListingWrapper()				
				jobListingInstance.id = xml.attributes()['id']?.toLong()
				jobListingInstance.setFromXML(it)
			  }
			  return [jobListingInstance: jobListingInstance]
			}
			
			response.failure = { resp ->
				flash.message = message(code: 'default.not.found.message', args: [message(code: path+".label", default: path.capitalize()), params.id])
				redirect(action: "list")
				return
			}
		}				             
    }

    def edit() {
        def jobListingInstance
		
		httpBuilder.request(rootPath, Method.GET, XML ) {
			uri.path = path + "/$params.id"			
			
			response.success = { resp, xml ->			  
			  xml.each {												
				jobListingInstance = new JobListingWrapper()				
				jobListingInstance.id = xml.attributes()['id']?.toLong()
				jobListingInstance.setFromXML(it)
			  }
			  return [jobListingInstance: jobListingInstance]
			}
			
			response.failure = { resp ->
				flash.message = message(code: 'default.not.found.message', args: [message(code: path+".label", default: path.capitalize()), params.id])
				redirect(action: "list")
				return
			}
		}
    }
	
}

public class JobListingWrapper extends JobListing {
	private Long id	
	
	public Long getId() {
		return id
	}
	
	public void setId(Long id) {
		this.id = id
	}
	
	public void setFromXML(def node) {
		
		node.childNodes().each {			
			if (it.name == "recruiter") {
				this."$it.name" = new UserWrapper()
				this."$it.name".id = it.attributes()['id'].toLong()
				it.each {				
					this."$it.name".setFromXML(it)
				}	
			} else if (it.text().isDouble()) {
				this."$it.name" = Double.parseDouble(it.text())
			} else if(it.name == "dateCreated" || it.name == "lastUpdated") {
				
			} else {
				this."$it.name" = it.text()
			}
		}		
	}	
}